import { Button, Swiper, SwiperItem, View,Image,Text } from '@tarojs/components'
import React, { useEffect, useState } from 'react'
import Taro, { useDidShow, useShareAppMessage } from '@tarojs/taro'
import { checkSalesMan } from '@/utils/Tools';
import { AtModal } from 'taro-ui'
import './index.scss'
import "taro-ui/dist/style/components/modal.scss";

export default function Index() {
  let capsuleInfo = {}
  if(process.env.TARO_ENV != 'h5') capsuleInfo = Taro.getMenuButtonBoundingClientRect()

  const [banner,setBanner] = useState([])
  const [swiperList,setSwiperList] = useState([])
  const [tabsList,setTabsList] = useState([])
  const [curTabs, setcurTabs] = useState(0)
  const [params,setParams] = useState({
    page:1,
    pageSize:10
  })
  const [hotList,setHotList] = useState([])
  const [moreStatus,setmoreStatus] = useState('more')
  const [location,setLocation] = useState({})
  const [otherList,setOtherList] = useState([])
  const [couponPopup,setCouponPopup] = useState(false)
  const [couponInfo,setCouponInfo] = useState({})

  const [curSwiper,setCurSwiper] = useState(0)
  const [swiperMargin, setSwiperMargin] = useState({
    movie: 0
  })

  useEffect(()=>{
    setSwiperMargin({
      movie: Taro.getSystemInfoSync().windowWidth*220/750
    })
    const {router} = Taro.getCurrentInstance()
    init()
    checkSalesMan(router.params)
    // Taro.$get('/wallet/app/fineCoupon/selectMyPromoTask').then(r=>{
    //   if(r.code == '1'){
    //     setCouponInfo(r.content || {})
    //     if(r.content && r.content.taskId){
    //       setCouponPopup(true)
    //     }
    //   }
    // })
  },[])
  useDidShow(()=>{
    Taro.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: '#000008'
    })
    Taro.$setTabbarList()
    Taro.eventCenter.off('updateLocation')
    Taro.eventCenter.on('updateLocation',(res)=>{
      updateLocation()
      init()
    })
    updateLocation()
  })
  useShareAppMessage(()=>{
    return {
      title: '影竞联盟',
      path: '/pages/index/index'
    }
  })
  function init(){
    Taro.$get('/act/index/selectAdvertisingListByAlias/_xjtsy').then(res=>{
      setSwiperList(res.content.advertisesList || [])
    })
    _initData()
  }
  function updateLocation(){
    const loca = Taro.getStorageSync('cityInfo')
    if(loca && loca.cityCode){
      setLocation(loca || {})
    }
  }
  function handleToBanner(e){
    if(process.env.TARO_ENV == 'h5'){
      if(e.url.includes('http')){
        location.href = e.url
      }else{
        Taro.navigateTo({
          url:e.url
        })
      }
      return;
    }
    if(e.url.includes('http')){
      Taro.navigateTo({
        url:`/pages/fineEngine/webView?url=${e.url}`
      })
      return;
    }
    Taro.navigateTo({
      url:e.url
    })
  }
  function handleToDetail(e){  ///   跳详情
    Taro.navigateTo({
      url:`/mainPages/event-detail/index?id=${e.id}`
    })
  }
  function handleCouponModel (){
    if (couponInfo.mode == 2) {
      setCouponPopup(false)
      return;
    }
    Taro.$post('/wallet/app/fineCoupon/receiveMyPromoTask',{taskId:couponInfo.taskId}).then(res=>{
      if (res.code === '1') {
        Taro.$toast('领取成功')
        setTimeout(()=>{
          setCouponPopup(false)
        },1000)
      } else {
        Taro.$toast(res.message)
      }
    })
  }

  const handleChangeSwiper = e=>{  ///   切换主题赛事
    setCurSwiper(e.detail.current)
    setcurTabs(0)
    setHotList([])
    setOtherList([])
  }
  function handleTabs(e){  //  切换日期
    setcurTabs(e)
    setParams({
      ...params,page:1
    })
    setOtherList([])
    _getEventList(tabsList[curSwiper].topicList[e])
  }

  useEffect(()=>{
    _getEventList(tabsList[curSwiper]?.topicList[0])
  },[curSwiper])
  
  ///      network
  const _initData = async ()=>{  //  获取活动列表
    const loca = Taro.getStorageSync('cityInfo')
    Taro.$get('/act/aggregation/topic',{
      flag:0,
      cityCode:loca.cityCode||0,
    }).then(res=>{
      setTabsList(res.content)
      if(res.content.length){
        _getEventList(res.content[curSwiper]?.topicList[curTabs])
      }
    })
  }
  const _getEventList = async (values,e) => {
    const loca = Taro.getStorageSync('cityInfo')
    const data = {
      cityCode:loca.cityCode||0,
      page:1,
      pageSize:100,
      topicId:values?.id
    }
    if(!values?.id) return;
    if(loca && loca.latitude){
      Object.assign(data,{
        latitude:loca.latitude,
        longitude:loca.longitude
      })
    }
    Taro.showLoading({title:'加载中...'})
    const res = await Taro.$post('/act/aggregation/list',data,'1')
    if(res.code == '1' && res.content.records.length){
      setHotList(res.content.records)
    }
    if(loca.cityCode != '0'){
      _getOtherEvent(values?.id)
    }
  }
  function _getOtherEvent(oid){  ///  获取其他城市列表
    const loca = Taro.getStorageSync('cityInfo')
    setmoreStatus('loading')
    let data = {
      // ...this.params,
      topicId:oid || tabsList[curSwiper]?.topicList[curTabs]?.id
    }
    if(loca && loca.latitude){
      Object.assign(data,{
        cityCode:loca.cityCode,
        latitude:loca.latitude,
        longitude:loca.longitude
      })
    }
    Taro.$post('/act/aggregation/otherCity',data).then(result=>{
      if(result.code === '1'){
        setOtherList(result.content)
        setmoreStatus('no-more')
      }
    })
  }
  
  return (
  <View>
    <View className={`home ${process.env.TARO_ENV}`}>
      <View className="home-crumbs" style={{'paddingTop': capsuleInfo.top+'px'}}>
        <View className="crumbs-main" style={{height: capsuleInfo.height+'px'}} onClick={()=>{
          Taro.navigateTo({
            url:'/mainPages/city-list/index'
          })
        }}>
          <Image src={require('@/static/Location.svg')} className="main-logo"></Image>
          <View className='h2' style={{whiteSpace:'nowrap'}}>{location?.name?.replace("市", "") || '全国'}</View>
          <Text className="at-icon at-icon-chevron-down" style={{color:'#fff',fontSize:14}}></Text>
        </View>
        {process.env.TARO_ENV == 'tt'?null:<>
        <View style={{whiteSpace:'nowrap'}}>影竞联盟</View>
        <View style={{width: capsuleInfo.width+'px'}}></View>
        </>}
      </View>
      {swiperList.length?<>
        {swiperList.length > 1?
        <View className="home-swiper banner">
          <Swiper className="swiper-main" autoplay={true} interval={3000} duration={1000}>
            {swiperList.map(item=>{
              return <SwiperItem key={item.id} onClick={()=>{handleToBanner(item)}}>
              <Image className="img" src={item.imageUrl} mode="aspectFill"></Image>
            </SwiperItem>
            })}
          </Swiper>
        </View>:
        <View style="margin: 16rpx 32rpx;"><Image className="swiper-img" src={swiperList[0].imageUrl} mode="aspectFill"></Image></View>}
      </>:null}

      {banner.length?
      <View className="home-list not-bar">
        {banner.map(item=>{
          return <View className="list-item" key={item} onClick={()=>{handleToDetail(item)}}>
          <Image className="item-img" src="https://img0.baidu.com/it/u=2685051271,176347936&fm=253&fmt=auto&app=138&f=JPEG?w=475&h=500" mode="aspectFill"></Image>
          <View className="item-info">
            <View className="dot h2">王者荣耀2023赛季全国影城直播...</View>
            <View className="box-flex p" style="align-items: center;"><Image className="info-icon" src={require('@/static/icon_time.png')} mode="aspectFill"></Image> 朝阳区 04/15 12:30</View>
            <View className="info-price">
              <Image className="info-icon" src={require('@/static/icon_map-pin.png')} mode="aspectFill"></Image>
              <View className='p'>保利国际影城北京马家...</View>
              <Text className="strong"><Text style="font-size: 20rpx;">￥</Text>27.99</Text>
            </View>
          </View>
        </View>
        })}
      </View>:null}
      <View className="home-tabs">
        <Swiper onChange={e=>{handleChangeSwiper(e)}} current={curSwiper} displayMultipleItems={1} previousMargin={swiperMargin.movie} nextMargin={swiperMargin.movie} className='tabs-swiper' >
          {tabsList.map((item, index) => {
            return <SwiperItem key={index} onClick={() => {setCurSwiper(index)}} >
              <View className={`swiper-box ${index === curSwiper ? 'active' : ''}`}>
                <Image className='swiper-img' src={item.imageUrl} mode='aspectFill' />
              </View>
            </SwiperItem>
          })}
        </Swiper>
        <View className="home-title h2">{hotList.length?tabsList[curSwiper]?.topicList[curTabs]?.title:tabsList[curSwiper]?.spareTitle}</View>
        <View className="tabs-list not-bar">
          {tabsList[curSwiper]?.topicList?.map((item,idx)=>{
            return <View className={`tabs-item ${curTabs == idx?'active':''}` } key={item.id} onClick={()=>{handleTabs(idx)}}>
            <View className='item-h2'>{item.dateStr}</View> <Text>{item.dateDesc}</Text>
          </View>
          })}
        </View>
      </View>
      {hotList.length?<View className="home-hot" style="padding-bottom: 0;">
        {hotList?.map(item=>{
          return <View className="hot-list" key={item.id} onClick={()=>{handleToDetail(item)}}>
          <View className="hot-item">
            <View className="h2">
              <View className='dot2'>{item.locationName}</View>
              {item.tagsJson?
              <View className="info-list">
                {item.tagsJson.map(tag=>{
                  return <Text className={`${tag.source == 'PLATFORM'?'red':''}`} key={tag.tagName}>{tag.tagName}</Text>
                })}
              </View>:null}
            </View>
            <View className="h4">
              <View className='dot'>{item.locationAddress}</View>
              {item.distance?<Text>距离{item.distance}</Text>:null}
            </View>
            <View className="list-item">
              <View className="item-time">
                <View className="item-h2">{item.startTimeStr}</View> {item.duration?`约${item.duration}分钟`:null}
              </View>
              {item.establishTickets?<View className="item-info">
                <View className="item-h2">{item.isEstablish?<>
                  <Image src={require('@/static/status-radio-selected@2x.png')}></Image> 已达开场人数
                </>:`${item.establishTickets}人开场${item.recordNum>0?'，已组'+item.recordNum+'人':''}`}</View>
                {item.endDateStr}截止
              </View>:null}
              <View className="item-price">
                <View className="strong">¥{item.price}<Text style={{fontSize:12,fontWeight:400}}>{item.areaPrice=='2'?'起':''}</Text></View> {item.isBirdDiscount == '1'?item.isBirdDiscountDesc:null}
              </View>
              <View className="item-button">购票</View>
            </View>
          </View>
        </View>
        })}
      </View>:
      <View className="var-empty">
        <View style="font-size: 32rpx;color:#fff;margin: 16rpx 0;">目前还没有场次安排</View>
        <View style="color:#A6A8AA;">后续会发布新的观赛场次，敬请期待哦~</View>
      </View>}
      {otherList.length && location.cityCode != '0'?<>
        <View className="other-title h2">附近城市活动</View>
        <View className="home-hot">
          {otherList.map(item=>{
            return <View className="hot-list" key={item.id} onClick={()=>{handleToDetail(item)}}>
            <View className="hot-item">
              <View className="h2">
                <View className='dot2'>{item.locationName}</View>
                {item.tagsJson?
                <View className="info-list">
                  {item.tagsJson.map(tag=>{
                    return <Text className={`${tag.source == 'PLATFORM'?'red':''}`} key={tag.tagName}>{tag.tagName}</Text>
                  })}
                </View>:null}
              </View>
              <View className="h4">
                <View className='dot'>{item.locationAddress}</View>
                {item.distance?<Text>距离{item.distance}</Text>:null}
              </View>
              <View className="list-item">
                <View className="item-time">
                  <View className="item-h2">{item.startTimeStr}</View> {item.duration?`约${item.duration}分钟`:null}
                </View>
                {item.establishTickets?<View className="item-info">
                  <View className="item-h2">{item.isEstablish?<>
                    <Image src={require('@/static/status-radio-selected@2x.png')}></Image> 已达开场人数
                  </>:`${item.establishTickets}人开场${item.recordNum>0?'，已组'+item.recordNum+'人':''}`}</View>
                  {item.endDateStr}截止
                </View>:null}
                <View className="item-price">
                  <View className="strong">¥{item.price}<Text style={{fontSize:12,fontWeight:400}}>{item.areaPrice=='2'?'起':''}</Text></View> {item.isBirdDiscount == '1'?item.isBirdDiscountDesc:null}
                </View>
                <View className="item-button">购票</View>
              </View>
            </View>
          </View>
          })}
        </View>
      </>:null}
    </View>
    {process.env.TARO_ENV != 'tt'?
    <View className="join-message">
      <Image onClick={()=>{
        Taro.navigateTo({
          url:'/pages/other/fans-base/index'
        })
      }} src={require('@/static/wechatgroup.png')} mode="widthFix" className="message-img"></Image>
    </View>:null}
    <AtModal isOpened={couponPopup && couponInfo.taskId}>
      <View className="coupon-popup">
        <View className="popup-title">
          {couponInfo.mode== '2'?'您的专属优惠券已到账':'您有专属优惠券可领取'}
        </View>
        <View className="popup-list">
          {couponInfo.relations?.map((item,idx)=>{
            return <View className="list-item" key={idx}>
            {item.type == 1 || item.type == 2?<View className="item-price"><Text style="font-size: 26rpx;">￥</Text>{item.discountAmount}</View>:<View className="item-price">{item.discountAmount}<Text style="font-size: 26rpx;">折</Text></View>}
            <View className="item-info">
              <View className="h2">{(item.type == 1 || item.type == 2 ? '商城' : '外卖') + item.productTypeName}</View>
              <View className="p">{item.minAmount > 0 ? '满' + item.minAmount + '元可用' : '无门槛'}</View>
              <View className="time">{item.timeString}</View>
            </View>
          </View>
          })}
        </View>
        <View className="popup-footer">
          <Button className="button" onClick={()=>{handleCouponModel()}}>{couponInfo.mode == 2 ? '我知道了' : '一键领取'}</Button>
        </View>
        <Text className="at-icon at-icon-close" style={{fontSize:36,color:'#fff',position: 'relative',left: '50%',marginLeft:'-18px'}} onClick={()=>{setCouponPopup(false)}}></Text>
      </View>
    </AtModal>
  </View>
  )
}
